package com.zhangxin.aiInterview.controller;

import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhangxin.aiInterview.annotation.AuthCheck;
import com.zhangxin.aiInterview.common.BaseResponse;
import com.zhangxin.aiInterview.common.DeleteRequest;
import com.zhangxin.aiInterview.common.ErrorCode;
import com.zhangxin.aiInterview.common.ResultUtils;
import com.zhangxin.aiInterview.constant.UserConstant;
import com.zhangxin.aiInterview.exception.BusinessException;
import com.zhangxin.aiInterview.exception.ThrowUtils;
import com.zhangxin.aiInterview.manager.work_flow.generate_avatar.GenerateAvatar;
import com.zhangxin.aiInterview.model.dto.user.*;
import com.zhangxin.aiInterview.model.entity.*;
import com.zhangxin.aiInterview.model.enums.UserRoleEnum;
import com.zhangxin.aiInterview.model.vo.LoginUserVO;
import com.zhangxin.aiInterview.model.vo.UserVO;
import com.zhangxin.aiInterview.model.vo.response.GetUserInterviewInfoResponse;
import com.zhangxin.aiInterview.service.*;
import com.zhangxin.aiInterview.service.impl.UserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 用户接口
 *

 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private ResumeService resumeService;
    @Resource
    private ExamService examService;
    @Resource
    private AiInterviewService aiInterviewService;
    @Resource
    private HrInterviewService hrInterviewService;
    @Resource
    private FullProcessInterviewService fullProcessInterviewService;


    // region 登录相关

    /**
     * 用户注册
     *
     * @param userRegisterRequest
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String belongingCompany = userRegisterRequest.getBelongingCompany();
        String role = userRegisterRequest.getRole();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, role, belongingCompany)) {
            return null;
        }
        long result = userService.userRegister(userRegisterRequest);
        return ResultUtils.success(result);
    }

    /**
     * 用户，管理员，招聘者登录并且保存用户使用身份（0-实习生，1-校招）
     *
     * @param userLoginRequest
     * @param request
     * @param userLoginRequest
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<LoginUserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        String role = userLoginRequest.getRole();
        Integer userInterviewRole = userLoginRequest.getUserInterviewRole();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //如果role为用户需要判断userInterviewRole的值是否为null
        if(role.equals(UserRoleEnum.USER.getValue()) && ObjUtil.isEmpty(userInterviewRole)) throw new BusinessException(ErrorCode.PARAMS_ERROR);
        LoginUserVO loginUserVO = userService.userLogin(userAccount, userPassword, role, userInterviewRole, request);
        return ResultUtils.success(loginUserVO);
    }

    /**
     * 获取用户面试身份（0-实习生，1-校招）
     * @param request
     * @return
     */
    @GetMapping("/get/userInterviewRole")
    public BaseResponse<Integer> getUserInterviewRole(HttpServletRequest request) {
        Integer userInterviewRole = userService.getUserInterviewRole(request);
        return ResultUtils.success(userInterviewRole);
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User user = userService.getLoginUser(request);
        LoginUserVO userVO = userService.getLoginUserVO(user);
        //如果身份为招聘者
        if(UserRoleEnum.RECRUITER.getValue().equals(user.getUserRole())) userVO.setCompany(user.getBelongingCompany());
        //如果身份为用户
        if(UserRoleEnum.USER.getValue().equals(user.getUserRole())) userVO.setSchool(user.getBelongingCompany());
        return ResultUtils.success(userVO);
    }

    // endregion

    // region 增删改查

    /**
     * 创建用户
     *
     * @param userAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest, HttpServletRequest request) {
        if (userAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userAddRequest, user);
        // 默认密码 12345678
        String defaultPassword = "12345678";
        String encryptPassword = DigestUtils.md5DigestAsHex((UserServiceImpl.SALT + defaultPassword).getBytes());
        user.setUserPassword(encryptPassword);
        boolean result = userService.save(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(user.getId());
    }

    /**
     * 删除用户
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 更新用户
     *
     * @param userUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest) {
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取用户（仅管理员）
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<User> getUserById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(user);
    }

    /**
     * 根据 id 获取包装类
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<UserVO> getUserVOById(long id, HttpServletRequest request) {
        BaseResponse<User> response = getUserById(id, request);
        User user = response.getData();
        return ResultUtils.success(userService.getUserVO(user));
    }

    /**
     * 分页获取用户列表（仅管理员）
     *
     * @param userQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<User>> listUserByPage(@RequestBody UserQueryRequest userQueryRequest) {
        long current = userQueryRequest.getCurrent();
        long size = userQueryRequest.getPageSize();
        Page<User> userPage = userService.page(new Page<>(current, size),
                userService.getQueryWrapper(userQueryRequest));
        return ResultUtils.success(userPage);
    }

    /**
     * 分页获取用户封装列表
     *
     * @param userQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<UserVO>> listUserVOByPage(@RequestBody UserQueryRequest userQueryRequest,
            HttpServletRequest request) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = userQueryRequest.getCurrent();
        long size = userQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<User> userPage = userService.page(new Page<>(current, size),
                userService.getQueryWrapper(userQueryRequest));
        Page<UserVO> userVOPage = new Page<>(current, size, userPage.getTotal());
        List<UserVO> userVO = userService.getUserVO(userPage.getRecords());
        userVOPage.setRecords(userVO);
        return ResultUtils.success(userVOPage);
    }

    // endregion

    /**
     * 更新个人信息
     *
     * @param userUpdateMyRequest
     * @param request
     * @return
     */
    @PostMapping("/update/my")
    public BaseResponse<Boolean> updateMyUser(@RequestBody UserUpdateMyRequest userUpdateMyRequest,
            HttpServletRequest request) {
        if (userUpdateMyRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        User user = new User();
        BeanUtils.copyProperties(userUpdateMyRequest, user);
        user.setId(loginUser.getId());
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 保存面试类型
     * @param type 面试类型（技术面，HR面）
     * @param request
     */
    @GetMapping("/save/interview/type")
    public void saveInterviewType(Integer type, HttpServletRequest request){
        userService.saveInterviewType(type,request);
    }

    /**
     * 生成头像
     * @param description
     * @return
     */
    @GetMapping("/generate/avatar")
    public BaseResponse<String> generateAvatar(String description) {
        return ResultUtils.success(GenerateAvatar.generateAvatar(description));
    }

    /**
     * 获取用户面试信息
     * @param userId
     * @return
     */
    @GetMapping("/get/interview/info")
    public BaseResponse<GetUserInterviewInfoResponse> getUserInterviewInfo(Long userId){
        //简历筛选次数
        Long resumeCount = resumeService.lambdaQuery()
                .eq(Resume::getUserId, userId)
                .count();
        //笔试次数
        Long examCount = examService.lambdaQuery()
                .eq(Exam::getUserId, userId)
                .count();
        //技术面试次数
        Long tecCount = aiInterviewService.lambdaQuery()
                .eq(AiInterview::getUserId, userId)
                .count();
        //HR面试次数
        Long hrCount = hrInterviewService.lambdaQuery()
                .eq(HrInterview::getUserId, userId)
                .count();
        //全流程面试次数
        Long fullProcessInterviewCount = fullProcessInterviewService.lambdaQuery()
                .eq(FullProcessInterview::getUserId, userId)
                .count();
        GetUserInterviewInfoResponse getUserInterviewInfoResponse = new GetUserInterviewInfoResponse();
        getUserInterviewInfoResponse.setResumeCount(resumeCount.intValue());
        getUserInterviewInfoResponse.setExamCount(examCount.intValue());
        getUserInterviewInfoResponse.setTecCount(tecCount.intValue());
        getUserInterviewInfoResponse.setHrCount(hrCount.intValue());
        getUserInterviewInfoResponse.setFullProcessInterviewCount(fullProcessInterviewCount.intValue());
        return ResultUtils.success(getUserInterviewInfoResponse);
    }
}